<template>
  <div class="reg_c">
    <form>
      <table
        border="0"
        style="width: 420px; font-size: 14px; margin-top: 20px"
        cellspacing="0"
        cellpadding="0"
      >
        <tr height="50" valign="top">
          <td width="95">&nbsp;</td>
          <td>
            <span class="fl" style="font-size: 24px">注册</span>
            <span class="fr"
              >已有商城账号，<router-link
                :to="{ name: 'Login' }"
                style="color: #ff4e00"
                >我要登录</router-link
              ></span
            >
          </td>
        </tr>
        <tr height="50">
          <td align="right">
            <font color="#ff4e00">*</font>&nbsp;登录用户名 &nbsp;
          </td>
          <td>
            <input
              type="text"
              value=""
              class="l_user"
              v-model="user.loginName"
              @input="debounceCheckLoginName"
              @focus="valid.loginName = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.loginName }}</td>
        </tr>
        <tr height="50">
          <td align="right"><font color="#ff4e00">*</font>&nbsp;密码 &nbsp;</td>
          <td>
            <input
              type="password"
              value=""
              class="l_pwd"
              v-model="user.password"
              @focus="valid.password = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.password }}</td>
        </tr>
        <tr height="50">
          <td align="right">
            <font color="#ff4e00">*</font>&nbsp;确认密码 &nbsp;
          </td>
          <td>
            <input
              type="password"
              value=""
              class="l_pwd"
              v-model="rePassword"
              @focus="valid.rePassword = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.rePassword }}</td>
        </tr>
        <tr height="50">
          <td align="right">
            <font color="#ff4e00">*</font>&nbsp;真实姓名 &nbsp;
          </td>
          <td>
            <input
              value=""
              class="l_pwd"
              v-model="user.userName"
              @focus="valid.userName = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.userName }}</td>
        </tr>
        <tr height="50">
          <td align="right"><font color="#ff4e00">*</font>&nbsp;性别 &nbsp;</td>
          <td>
            <input
              type="radio"
              name="sex"
              value="1"
              v-model="user.sex"
            />男<input type="radio" name="sex" value="0" v-model="user.sex" />女
          </td>
        </tr>
        <tr height="50">
          <td align="right"><font color="#ff4e00">*</font>身份证号 &nbsp;</td>
          <td>
            <input
              type="text"
              value=""
              class="l_num"
              v-model="user.identityCode"
              @focus="valid.identityCode = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.identityCode }}</td>
        </tr>
        <tr height="50">
          <td align="right"><font color="#ff4e00">*</font>&nbsp;邮箱 &nbsp;</td>
          <td>
            <input
              type="text"
              value=""
              class="l_email"
              v-model="user.email"
              @focus="valid.email = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.email }}</td>
        </tr>
        <tr height="50">
          <td align="right"><font color="#ff4e00">*</font>&nbsp;手机 &nbsp;</td>
          <td>
            <input
              type="text"
              value=""
              class="l_tel"
              v-model="user.mobile"
              @focus="valid.mobile = ''"
            />
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.mobile }}</td>
        </tr>
        <tr height="50">
          <td align="right">
            <font color="#ff4e00">*</font>&nbsp;邮箱验证码 &nbsp;
          </td>
          <td>
            <input
              type="text"
              value=""
              class="l_ipt"
              @focus="valid.emailValidCode = ''"
              v-model="user.emailValidCode"
            />&nbsp;&nbsp;
            <!-- 获取验证码按钮 -->
            <el-button type="danger" @click="getValidationCode">{{
              buttonText
            }}</el-button>
          </td>
        </tr>
        <tr v-show="!valid.canSubmit">
          <td>&nbsp;</td>
          <td class="errTxt">{{ valid.emailValidCode }}</td>
        </tr>
        <!-- <tr>
          <td>&nbsp;</td>
          <td style="font-size: 12px; padding-top: 20px">
            <span style="font-family: '宋体'" class="fl">
              <label class="r_rad"><input type="checkbox" /></label
              ><label class="r_txt">我已阅读并接受《用户协议》</label>
            </span>
          </td>
        </tr> -->
        <tr height="60">
          <td>&nbsp;</td>
          <td>
            <input
              type="button"
              @click="submit"
              value="立即注册"
              class="log_btn"
            />
          </td>
        </tr>
      </table>
    </form>
  </div>
</template>
<script>
import Vue from "vue";
import { Button } from "element-ui";
Vue.use(Button);
export default {
  data() {
    return {
      user: {
        loginName: "",
        userName: "",
        password: "",
        sex: 1,
        identityCode: "",
        email: "",
        mobile: "",
        emailValidCode: "",
      },
      rePassword: "",
      
      valid: {
        canSubmit: false,
        loginName: "",
        userName: "",
        password: "",
        rePassword: "",
        sex: "",
        identityCode: "",
        email: "",
        mobile: "",
        emailValidCode: "",
        loginNameExist: false,
      },
      buttonText: "获取验证码",
      isCoding: false, //是否正在发送验证码
      countDown: 60, //验证倒计时60s
      timer: null, //定时器，方便清除
      sessionStorage: window.sessionStorage
    };
  },
  methods: {
    submit() {
      //数据校验
      let canSubmit = true;
      if (this.user.loginName === "") {
        this.valid.loginName = "用户登录名不能为空";
        canSubmit = false;
      }
      if (this.user.password === "") {
        this.valid.password = "密码不能为空";
        canSubmit = false;
      }
      if (this.rePassword === "") {
        this.valid.rePassword = "确认密码不能为空";
        canSubmit = false;
      } else if (this.rePassword !== this.user.password) {
        this.valid.rePassword = "两次密码输入不一致";
        canSubmit = false;
      }
      if (this.user.email === "") {
        this.valid.email = "邮箱不能为空";
        canSubmit = false;
      }else {
        // 邮箱格式校验
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailRegex.test(this.user.email)) {
          this.valid.email = "邮箱格式不正确";
          canSubmit = false;
        }
      }
      if (this.user.mobile === "") {
        this.valid.mobile = "手机号不能为空";
        canSubmit = false;
      } else {
        // 手机号格式校验
        const mobileRegex = /^1[3-9]\d{9}$/;
        if (!mobileRegex.test(this.user.mobile)) {
          this.valid.mobile = "手机号格式不正确";
          canSubmit = false;
        }
      }

      if (this.user.identityCode === "") {
        this.valid.identityCode = "身份证号不能为空";
        canSubmit = false;
      } else {
        // 身份证号格式校验
        const identityCodeRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        if (!identityCodeRegex.test(this.user.identityCode)) {
          this.valid.identityCode = "身份证号格式不正确";
          canSubmit = false;
        }
      }
      if (this.user.userName === "") {
        this.valid.userName = "真实姓名不能为空";
        canSubmit = false;
      }
      if (this.user.emailValidCode === "") {
        this.valid.emailValidCode = "邮箱验证码不正确";
        canSubmit = false;
      }
      this.valid.canSubmit = canSubmit;
      console.log(this.valid.canSubmit, this.valid.loginNameExist)
      if (!this.valid.canSubmit || this.valid.loginNameExist) return;

      console.log("submit", this.user);
      this.$axios({
        url: "/api/user/adduser",
        method: "POST",
        data: this.user,
      }).then((rs) => {
        if(rs.data.code == "5000") {
          this.valid.canSubmit = false;
          this.valid.emailValidCode = rs.data.emailValidCode;
        }
        else{
          this.$router.push({name: "Login"});
        }
      });
    },
    checkLoginName() {
      if (!this.user.loginName) return;
      this.$axios({
        url: "/api/user/find",
        method: "post",
        data: {
          loginName: this.user.loginName,
        },
      }).then((rs) => {
        console.log(rs);
        if (rs.data.code === 5200) {
          this.valid.loginName = "用户登录名已存在";
          this.valid.canSubmit = false;
          this.valid.loginNameExist = true;
        } else {
          this.valid.loginNameExist = false;
          this.valid.loginName = "";
        }
      });
    },
    debounce(func, delay) {
      //自定义防抖执行@input校验登录名事件
      let timer = null;
      return function () {
        clearTimeout(timer); // 清除之前的计时
        timer = setTimeout(() => {
          func.apply(this, arguments); // 延迟执行
        }, delay);
      };
    },
    getValidationCode() {
      //发送验证码
      //校验邮箱不为空
      if (!this.user.email) {
        this.valid.email = "邮箱不能为空";
        this.canSubmit = false;
        return;
      }
      if (this.isCoding) return;
      this.isCoding = true;
      this.timer = setInterval(() => {
        this.buttonText = `(${this.countDown})s后重新获取`;
        this.countDown--;
        if (this.countDown <= 0) {
          //恢复未点击时的状态
          this.isCoding = false;
          this.buttonText = "重新获取";
          this.countDown = 60;
          clearInterval(this.timer)
        }
      }, 1000);
      //发送邮箱验证码获取请求
      this.$axios({
        url: "/api/email",
        method: "post",
        data: {
          emailAddress: this.user.email,
        },
      })
        .then((rs) => {
          console.log(rs);
        })
        .catch((error) => {
          console.error("发送失败:", error);
          this.$message.error("验证码发送失败，请重试或联系管理员");
        });
    },
  },
  created() {
    this.debounceCheckLoginName = this.debounce(this.checkLoginName, 500);
    if(this.sessionStorage.getItem("loginName") != null) {
      this.$router.push({name: "IndexCenter"})
    }
  },
  destroyed() {
    clearInterval(this.timer);
    console.log("销毁了计时器");
  },
};
</script>

<style scope>
.errTxt {
  color: red;
  font-size: 0.8rem;
}
</style>